<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <!-- 上传初始化数据 -->
  <el-dialog v-if="dialogVisible" v-model="dialogVisible" title="上传初始化数据" width="600px" append-to-body>
    <el-form ref="dialogFormRef" :model="dialogForm" :rules="rules" label-width="80px">
      <el-form-item label="所属机型" prop="aircraftModel">
        <el-select v-model="dialogForm.aircraftModel" width="220px" clearable>
          <el-option v-for="item in airModelList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属批次" prop="track">
        <el-input v-model="dialogForm.track" placeholder="请输入批次号" maxlength="20" />
      </el-form-item>
      <el-form-item label="初始文件" prop="file" style="width: '100%'">
        <el-upload
          ref="uploadRef"
          action="#"
          accept=".zip"
          :auto-upload="false"
          :on-change="changeFile"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :limit="1"
        >
          <el-button type="primary">上传文件</el-button>
          <template #tip>
            <div class="el-upload__tip">初始文件只支持压缩包.zip格式的文件上传。</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注" prop="desc">
        <el-input v-model="dialogForm.desc" type="textarea" :autosize="{ minRows: 2 }" width="220px" placeholder="请输入"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" @click="handleCancel">取 消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="handleSave">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="UploadInitDataDialog" lang="ts">
import { getStructureTree } from '@/api/elementsLibrary/index';
import { genFileId } from 'element-plus';
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
import { uploadInit } from '@/api/bomCompareTool/standardInstallationList/index';
import { getEventInfo } from '@/api/bomCompareTool/originInstallationList/index';
const emit = defineEmits(['on-sure']);
const { proxy } = getCurrentInstance();
const uploadRef = ref<UploadInstance>();
const airModelList = ref([]);
const dialogVisible = ref(false);
const dialogFormRef = ref();
const buttonLoading = ref(false);
const dialogForm = reactive({
  aircraftModel: '',
  desc: '初始标准装机清单和强度数模清单',
  track: '',
  file: ''
});
const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
};
const rules = reactive<ElFormRules>({
  aircraftModel: [{ required: true, message: '机型不能为空', trigger: 'change' }],
  desc: [{ required: true, message: '备注不能为空', trigger: 'change' }],
  track: [{ required: true, message: '批次号不能为空', trigger: 'change' }],
  file: [{ required: true, message: '文件不能为空', trigger: 'change' }]
});
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  dialogForm.file = null;
  dialogFormRef.value.validateField(['file']);
};
const changeFile = (data) => {
  if (data.status === 'ready') {
    dialogForm.file = data.raw;
    dialogFormRef.value.validateField(['file']);
  }
};
const modelList = async () => {
  const res = await getStructureTree();
  airModelList.value = res.data.map((item) => {
    return {
      value: item.mark,
      label: item.name
    };
  });
};
const handleCancel = () => {
  dialogVisible.value = false;
};
const handleSave = async () => {
  await dialogFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      buttonLoading.value = true;
      const formData = new FormData();
      formData.append('aircraftModel', dialogForm.aircraftModel);
      formData.append('track', dialogForm.track);
      formData.append('file', dialogForm.file);
      formData.append('desc', dialogForm.desc);
      const res = await uploadInit(formData).catch(() => {
        buttonLoading.value = false;
      });
      const timer = setInterval(async () => {
        const ids = res.data.join(',');
        const datas = await getEventInfo({ ids: ids }).catch(() => {
          clearInterval(timer);
          buttonLoading.value = false;
        });
        const data = datas[0];
        proxy?.$modal.msg(`${data.currentInfo}`);
        if (data.status === 'DONE' || data.status === 'FAIL' || data.status === 'NONE_MATCH') {
          clearInterval(timer);
          proxy?.$modal.msgSuccess('上传初始化数据成功！');
          emit('on-sure');
          dialogVisible.value = false;
          buttonLoading.value = false;
        }
      }, 1000);
    } else {
      proxy?.$modal.msgError('请填写完整数据！');
    }
  });
};
const openDialog = () => {
  dialogForm.aircraftModel = '';
  dialogForm.desc = '初始标准装机清单和强度数模清单';
  dialogForm.track = '';
  dialogForm.file = '';
  dialogVisible.value = true;
};
defineExpose({
  openDialog
});
onMounted(() => {
  modelList();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: center;
}
</style>
